import { DataSource } from 'typeorm';

import { Permission } from '@src/permission/entity/permission.entity';
import { Role } from '@src/role/entity/role.entity';
import { User } from '@src/user/entity/user.entity';

export async function seedAdmin(dataSource: DataSource) {
  const permissionRepo = dataSource.getRepository(Permission);
  const roleRepo = dataSource.getRepository(Role);
  const userRepo = dataSource.getRepository(User);

  /* 1. 拿到所有权限 */
  const allPermissions = await permissionRepo.find();

  /* 2. 创建/更新超级管理员角色 */
  let adminRole = await roleRepo.findOne({
    where: { name: 'admin' },
    relations: ['permissions'],
  });
  if (!adminRole) {
    adminRole = roleRepo.create({
      name: 'admin',
      description: '超级管理员',
      permissions: allPermissions,
    });
    adminRole = await roleRepo.save(adminRole);
  } else {
    adminRole.permissions = allPermissions;
    await roleRepo.save(adminRole);
  }

  /* 3. 创建/更新超级管理员用户（幂等） */
  const username = 'admin';
  let admin = await userRepo.findOne({ where: { username } });
  if (!admin) {
    admin = userRepo.create({
      password: 'admin',
      username: 'admin',
      roles: [adminRole],
    });
    await userRepo.save(admin);
  } else {
    admin.roles = [adminRole];
    await userRepo.save(admin);
  }
}
